package io.gitee.zicai.service.consumer.controller

import io.gitee.zicai.service.common.IHelloService
import io.gitee.zicai.service.common.enum.RpcType
import io.gitee.zicai.service.consumer.feign.HelloFeign
import org.apache.dubbo.config.annotation.Reference
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
import kotlin.system.measureTimeMillis

/**
 * HelloController
 * @author zicai
 * @since 2019-12-05
 */
@RestController
@RequestMapping("/hello")
open class HelloController {

    private val log = LoggerFactory.getLogger(this::class.java)

    @Reference
    private lateinit var helloService: IHelloService
    @Autowired
    private lateinit var helloFeign: HelloFeign
    @Autowired
    private lateinit var restTemplate: RestTemplate
    @Value("\${dubbo.cloud.subscribed-services:'service-provider'}")
    private lateinit var serviceProvider: String

    @GetMapping("/msg/{msg}")
    open fun msg(@PathVariable msg: String) : String {
        var result: String? = ""
        return measureTimeMillis {
            result = when(RpcType.of(msg)) {
                RpcType.DUBBO -> helloService.hello(msg)
                RpcType.RIBBON -> restTemplate.getForObject("http://${serviceProvider}/hello/m/$msg", String::class.java)
                RpcType.FEIGN -> helloFeign.hello(msg)
                else -> msg
            }
        }.let {
            "$result , time -> $it"
        }.also {
            log.info("consumer -> $it")
        }
    }

    @GetMapping("/config/{msg}")
    open fun config(@PathVariable msg: String) : String {
        var result: String? = ""
        return measureTimeMillis {
            result = when(RpcType.of(msg)) {
                RpcType.DUBBO -> helloService.config()
                RpcType.RIBBON -> restTemplate.getForObject("http://${serviceProvider}/hello/config", String::class.java)
                RpcType.FEIGN -> helloFeign.config()
                else -> "localConsumerValue000"
            }
        }.let {
            "$result , time -> $it"
        }.also {
            log.info("consumer -> $it")
        }
    }
}